<template>
  <div class="report-container">
    <!-- 实时诊断信息 -->
    <section class="diagnosis-section">
      <h2 class="section-title">实时诊断信息</h2>
      <div class="diagnosis-results">
        <div class="eye-result">
          <h3>左眼诊断结果</h3>
          <p>{{ diagnosisInfo.leftDiseaseResults.join(", ") }}</p>
        </div>
        <div class="eye-result">
          <h3>右眼诊断结果</h3>
          <p>{{ diagnosisInfo.rightDiseaseResults.join(", ") }}</p>
        </div>
      </div>
    </section>

    <!-- 预约查询 -->
    <section class="appointment-section">
      <h2 class="section-title">预约查询</h2>
      <el-table :data="appointments" class="data-table">
        <el-table-column prop="doctorName" label="医生姓名" width="180" />
        <el-table-column prop="appointmentTime" label="预约时间" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="statusMap[row.status]?.color">
              {{ statusMap[row.status]?.text }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </section>

    <!-- 报告查询 -->
    <section class="report-section">
      <h2 class="section-title">报告查询</h2>
      <el-table :data="reports" class="data-table">
        <el-table-column prop="recordId" label="报告ID" width="120" />
        <el-table-column prop="createTime" label="报告时间" />
        <el-table-column label="操作" width="260">
          <template #default="{ row }">
            <div class="action-group">
              <el-select
                v-model="row.selectedFormat"
                placeholder="选择格式"
                class="format-select"
              >
                <el-option label="PDF" value="PDF" />
                <el-option label="PNG" value="PNG" />
                <el-option label="HTML" value="HTML" />
              </el-select>
              <el-button
                type="primary"
                @click="handleDownloadReport(row.recordId, row.selectedFormat)"
              >
                下载报告
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, watch } from "vue";
const instance = getCurrentInstance();
const proxy = instance?.proxy as any;

import { usePatientDiagnosisStore } from "@/stores/patientDiagnosisStore";
const patientDiagnosisStore = usePatientDiagnosisStore();
const patientData = patientDiagnosisStore.getPatientInfo();
import { DoctorInfo } from "@/types/user";
import { RequestParams } from "@/types/request";
import { PatientAppointmentItem } from "@/types/patient";
import { PatientAllReports } from "@/types/imageAndFile";

const props = defineProps<{ doctors: DoctorInfo[] }>();

const appointments = ref<PatientAppointmentItem[]>([]);
const reports = ref<PatientAllReports[]>([]);
const diagnosisInfo = ref({
  leftDiseaseResults: [],
  rightDiseaseResults: [],
});

//模拟诊断数据，具体应该使用SSE
const mockDiagnosisData: any = [
  {
    leftDiseaseResults: ["糖尿病视网膜病变", "其他异常", "近视相关病变"],
    rightDiseaseResults: ["正常"],
  },
  {
    leftDiseaseResults: ["正常"],
    rightDiseaseResults: ["青光眼", "AMD", "其他异常"],
  },
  {
    leftDiseaseResults: ["白内障", "近视相关病变"],
    rightDiseaseResults: ["高血压视网膜病变", "白内障", "其他异常"],
  },
  {
    leftDiseaseResults: ["AMD", "糖尿病视网膜病变"],
    rightDiseaseResults: ["青光眼", "白内障", "其他异常"],
  },
];

// 预约状态映射
const statusMap: any = {
  PENDING: { text: "待确认", color: "warning" },
  CONFIRMED: { text: "已确认", color: "success" },
  CANCELLED: { text: "已取消", color: "danger" },
};

const fetchAppointments = async () => {
  try {
    let result: any = await proxy.request({
      method: "get",
      url: proxy.api.patientsAppointmentList,
      params: {} as RequestParams,
      headers: {
        token: patientData.token,
      },
    });
    if (!result) {
      return;
    }
    if (result.code === 1) {
      appointments.value = result.data.map(
        (appointment: PatientAppointmentItem) => ({
          ...appointment,
          doctorName:
            props.doctors.find((d) => d.id === appointment.doctorId)
              ?.username || "匿名医生",
        })
      );
    } else {
      proxy.message.warning("获取预约列表失败");
    }
  } catch (error) {
    proxy.message.error("获取预约列表失败，请检查网络连接");
  }
};

const fetchReports = async () => {
  try {
    let result: any = await proxy.request({
      method: "get",
      url: proxy.api.patientsReport,
      params: {} as RequestParams,
      headers: {
        token: patientData.token,
      },
    });
    if (!result) {
      return;
    }
    if (result.code === 1) {
      reports.value = result.data.map((report: PatientAllReports) => ({
        ...report,
        selectedFormat: "PDF", //默认格式
      }));
    } else {
      proxy.message.warning("获取报告列表失败");
    }
  } catch (error) {
    proxy.message.error("获取报告列表失败，请检查网络连接");
  }
};

const handleDownloadReport = async (
  reportId: number,
  format: "PDF" | "PNG" | "HTML"
) => {
  try {
    let result: any = await proxy.request({
      method: "get",
      url: proxy.api.patientsDownload + `/${reportId}`,
      params: {
        format: format,
      } as RequestParams,
      headers: {
        token: patientData.token,
      },
      responseType: "blob",
    });
    if (!result) {
      return;
    }
    const contentType = result.headers["content-type"];
    if (result.status === 200) {
      if (contentType.includes("application/json")) {
        const reader = new FileReader();
        reader.onload = () => {
          proxy.message.error("下载诊断报告失败");
        };
        reader.readAsText(result.data);
      } else {
        //blob
        const blob = new Blob([result.data], { type: contentType });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = `report.${format.toLowerCase()}`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        proxy.message.success("下载诊断报告成功");
      }
    } else {
      proxy.message.warning("下载诊断报告失败");
    }
  } catch (error) {
    proxy.message.error("下载诊断报告失败，请检查网络连接");
  }
};

onMounted(() => {
  const randomIndex = Math.floor(Math.random() * mockDiagnosisData.length);
  diagnosisInfo.value = mockDiagnosisData[randomIndex];
});

onMounted(async () => {
  await fetchAppointments();
  await fetchReports();
});

// 监听医生数据变化
watch(
  () => props.doctors,
  () => {},
  { immediate: true, deep: true }
);
</script>

<style scoped>
.report-container {
  padding: 24px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
  margin-bottom: 24px;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
  border-left: 4px solid #409eff;
  padding-left: 12px;
}

.diagnosis-results {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  margin-bottom: 32px;
}

.eye-result {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.eye-result h3 {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 16px;
}

.eye-result p {
  margin: 0;
  color: #409eff;
  font-weight: 500;
}

.data-table {
  margin-bottom: 32px;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.action-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.format-select {
  width: 120px;
}
</style>
